package com.chenjj.bigdata.solr.client;

import com.chenjj.bigdata.solr.client.impl.SolrCloudClientImpl;
import com.chenjj.bigdata.solr.client.impl.SolrHttpClientImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class SolrClientFactoryBean {
	private ConcurrentMap<String, SolrClient> clientInstanceMap = new ConcurrentHashMap<String, SolrClient>();
	private Logger logger = LoggerFactory.getLogger(getClass());
	private String solrServerAddress;
	
	@SuppressWarnings("unused")
	private SolrClientFactoryBean(){}
	
	public SolrClientFactoryBean(String _solrServerAddress){
		this.solrServerAddress = _solrServerAddress;
	}
	/**
	 * getSolrHttpClient
	 * @param coreName 
	 * @return
	 */
	public synchronized SolrClient getSolrHttpClient(String coreName){
		SolrClient client = clientInstanceMap.get(coreName);
		if(client == null){
			logger.info("solr http client {} not found in cahce,create and return it.",coreName);
			client = new SolrHttpClientImpl(solrServerAddress,coreName);
			clientInstanceMap.put(coreName, client);
		}else{
			logger.info("solr http client {} found in cache,return it. ",coreName);
		}
		return client;
	}
	
	/**
	 * getSolrCloudClient
	 * @param coreName 
	 * @return
	 */
	public synchronized SolrClient getSolrCloudClient(String coreName){
		SolrClient client = clientInstanceMap.get(coreName);
		if(client == null){
			logger.info("solr cloud client {} not found in cahce,create and return it.",coreName);
			client = new SolrCloudClientImpl(solrServerAddress,coreName);
			clientInstanceMap.put(coreName, client);
		}else{
			logger.info("solr cloud client {} found in cache,return it. ",coreName);
		}
		return client;
	}
	
	
	public void releaseAllResource(){
		Set<String> keySet = clientInstanceMap.keySet();
		for (String key : keySet) {
			SolrClient client = clientInstanceMap.get(key);
			client.close();
			logger.info("solr client {} closed ",key);
		}
	}
}
